package utils

import (
	"bytes"
	"strings"
	"unicode"
)

func Title(str string) string {
	var prev = ' '
	var isWordSeparator = func(r rune) bool {
		if r < 128 {
			switch {
			case '0' <= r && r <= '9':
				return false
			case 'a' <= r && r <= 'z':
				return false
			case 'A' <= r && r <= 'Z':
				return false
			case r == '_':
				return false
			}
			return true
		}
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			return false
		}
		return unicode.IsSpace(r)
	}

	return strings.Map(func(r rune) rune {
		if isWordSeparator(prev) {
			prev = r
			return unicode.ToTitle(r)
		}
		prev = r
		return r
	}, str)
}

func CamelCase(name string) string {
	name = strings.ReplaceAll(name, "_", " ")
	return strings.ReplaceAll(Title(name), " ", "")
}

func Capitalize(str string) string {
	buff := []byte(str)
	if buff[0] >= 'a' && buff[0] <= 'z' {
		buff[0] -= 32
		return string(buff)
	} else {
		return str
	}
}

func UnderScoreCase(name string) string {
	buffer := bytes.Buffer{}
	for i, v := range name {
		if unicode.IsUpper(v) {
			if i > 0 {
				buffer.WriteRune('_')
			}
			buffer.WriteRune(unicode.ToLower(v))
		} else {
			buffer.WriteRune(v)
		}
	}
	return buffer.String()
}
